package com.mayi.zds.web;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.mayi.zds.entity.User;
import com.mayi.zds.service.UserService;
import com.mayi.zds.utils.CodeUtil;
import com.mayi.zds.utils.GetComputerIP;
import com.mayi.zds.utils.RegexUtil;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @ClassName UserController
 * @Author zhong
 * @Date 2019/12/24 12:02:07
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String register(){
        return "register";
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/sendPhoneCode")
    @ResponseBody
    public String code(String telphone,int type){
        System.out.println(type);
        System.out.println(telphone);
        if (!telphone.matches(RegexUtil.REGEX_MOBILE)) {
            return "请输入正确11位手机号";
        }
        // 短信应用SDK AppID
        int appid = 1400238747; // 1400开头

        // 短信应用SDK AppKey
        String appkey = "1b1c67bb67f87d9774c095b896493674";

        // 需要发送短信的手机号码
        String[] phoneNumbers = {telphone};

        // 短信模板ID，需要在短信应用中申请
        // NOTE: 这里的模板ID`7839`只是一个示例，
        // 真实的模板ID需要在短信控制台中申请
        int templateId = 0;
        if (type == 1) {
            templateId = 385107;
        }else if (type == 2) {
            templateId = 385107;
        }else if (type == 3) {
            templateId = 385107;
        }


        // 签名
        // NOTE: 这里的签名"腾讯云"只是一个示例，
        // 真实的签名需要在短信控制台中申请，另外
        // 签名参数使用的是`签名内容`，而不是`签名ID`
        String smsSign = "yogafire";

        // 指定模板ID单发短信
        try {
            int code = (int) (Math.random()*9000+1000);
            String param = Integer.toString(code);
            CodeUtil.code.put(telphone,param);
            String[] params = {param};
            System.out.println(params[0]);
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumbers[0],
                    templateId, params, smsSign, "", "");
            System.out.println(result);
        } catch (HTTPException e) {
            // HTTP响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            // json解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        }
        return "验证码发送成功";
    }

    @PostMapping("/register")
    @ResponseBody
    public String register(User user, String code){
        System.out.println(user);
        if(!RegexUtil.isEmail(user.getEmail())){
            return "邮箱格式错误";
        }
        String realCode = CodeUtil.code.get(user.getAccount());
        if (!realCode.equals(code)){
            return "验证码输入错误";
        }else {
            CodeUtil.code.remove(user.getAccount());
            int result = userService.add(user);
            if (result == 0){
                return "该手机已经注册";
            }
        }
        return "注册成功";
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(User user, String code, HttpServletRequest request){
        if (user == null){
            return "error";
        }
        if (!code.equalsIgnoreCase((String) request.getSession().getAttribute("loginPic"))){
            return "验证码输入错误";
        }
        String result = userService.login(user);
        if (result.equals("登录成功")){
            HttpSession session = request.getSession();
            session.setAttribute("user",userService.getUserByAccountAndPassword(user.getAccount(),user.getPassword()));
            User user1 = new User();
            user1.setId(userService.getUserByAccountAndPassword(user.getAccount(),user.getPassword()).getId());
            user1.setLastloginIp(GetComputerIP.getIpAddr(request));
            user1.setLastloginTime(new Date());
            userService.update(user1);
            return user.getAccount();
        }else {
            return result;
        }
    }

    @GetMapping("center")
    public String center(@SessionAttribute(value = "user",required = false) User user, Model model, HttpSession session){
        session.setAttribute("user",userService.getUserByAccount("18011162609"));
        user = userService.getUserByAccount("18011162609");
        int orderNum = userService.getOrderNum(user.getId());
        int orderSuccessNum = userService.getSuccessOrderNum(user.getId());
        int couponNum = userService.getCouponNum(user.getId());
        model.addAttribute("orderNum",orderNum);
        model.addAttribute("orderSuccessNum",orderSuccessNum);
        model.addAttribute("couponNum",couponNum);
        return "member_index";
    }

    @GetMapping("coupon")
    public String coupon(){

        return "gifts";
    }

}
